package com.wms.common.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@MappedTypes(Long[].class)
@MappedJdbcTypes(JdbcType.ARRAY)
public class LongArrayTypeHandler extends BaseTypeHandler<Long[]> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Long[] parameter, JdbcType jdbcType) throws SQLException {
        Connection connection = ps.getConnection();
        Array array = connection.createArrayOf("bigint", parameter);
        ps.setArray(i, array);
    }

    @Override
    public Long[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return getLongArray(rs.getArray(columnName));
    }

    @Override
    public Long[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return getLongArray(rs.getArray(columnIndex));
    }

    @Override
    public Long[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return getLongArray(cs.getArray(columnIndex));
    }

    private Long[] getLongArray(Array array) throws SQLException {
        if (array == null) {
            return null;
        }
        Object[] objArray = (Object[]) array.getArray();
        List<Long> longList = new ArrayList<>();
        for (int i = 0; i < objArray.length; i++) {
            if (!Objects.isNull(objArray[i])) {
                longList.add((Long) objArray[i]);
            }
        }
        Long[] longArray = new Long[longList.size()];

        return longList.toArray(longArray);
    }
}